package com.chipcoo.velocity;

import com.chipcoo.utils.StringUtils;
import com.chipcoo.ResponseResult;
import org.apache.velocity.context.Context;
import org.apache.velocity.tools.Scope;
import org.apache.velocity.tools.ToolManager;
import org.apache.velocity.tools.view.ViewToolContext;
import org.springframework.web.servlet.view.velocity.VelocityLayoutView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

public class VelocityLayout2View extends VelocityLayoutView {
    @Override
    protected Context createVelocityContext(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) throws Exception {

        ViewToolContext ctx;
        ctx = new ViewToolContext(getVelocityEngine(), request, response,getServletContext());


        if(!model.containsKey("responseResult")) {
            ctx.putAll(model);
        }else {
            for (Map.Entry<String, Object> entry : model.entrySet()) {
                if (!"responseResult".equals(entry.getKey())) {
                    ctx.put(entry.getKey(), entry.getValue());
                } else {
                    Object objectResponseResult = entry.getValue();
                    if (null != objectResponseResult) {
                        ResponseResult<?> responseResult = (ResponseResult<?>) objectResponseResult;
                        //if (responseResult.getCode() == 0) {
                        ctx.put("model", responseResult.getData());
                        //} else {
                        if(responseResult.getCode()!=0) {
                            if (!StringUtils.isEmpty(responseResult.getMessage())) {
                                ctx.put("pageFailure", responseResult.getMessage());
                            } else ctx.put("pageFailure", responseResult.getCode());
                        }
                        //}
                    }
                }
            }
        }

        if (this.getToolboxConfigLocation() != null) {
            ToolManager tm = new ToolManager();


            tm.setVelocityEngine(getVelocityEngine());
            tm.configure(getServletContext().getRealPath(getToolboxConfigLocation()));

            if (tm.getToolboxFactory().hasTools(Scope.REQUEST)) {
                ctx.addToolbox(tm.getToolboxFactory().createToolbox(Scope.REQUEST));
            }
            if (tm.getToolboxFactory().hasTools(Scope.APPLICATION)) {
                ctx.addToolbox(tm.getToolboxFactory().createToolbox(Scope.APPLICATION));
            }
            if (tm.getToolboxFactory().hasTools(Scope.SESSION)) {
                ctx.addToolbox(tm.getToolboxFactory().createToolbox(Scope.SESSION));
            }

        }

        return ctx;
    }
}
